package com.musiklegal;

import java.io.IOException;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class CatalogueList extends Activity 
{
	ListView lvc;
	TextView tv;
	int offset=1;
	static MerchantEntity thismerchant;
	String temp="fachr1";
	static String name; 
	ProgressDialog dialog;
	InterfaceAdapter adapter2;
	HttpClient tinfo; 
	HttpGet gets;
	HttpResponse hrep;
	HttpEntity trinfo;
	SAXParserFactory spf;
	CatalogueParser cp;
	SAXParser sp ;
	XMLReader xr;
	//static String addres;
	static Address addres;
	static String srch;
  	static MerchantEntity merchant=null;
	boolean loading=false;
	Handler h;
	
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		h = new Handler();
		if(MusikLegal.internet(getApplicationContext())){
		setContentView(R.layout.catalogue);
		tinfo = new DefaultHttpClient(); 
		cp = new CatalogueParser();
		if(!TrackInfo.fromFriend)
		catalogue();
		else if(TrackInfo.fromFriend)
		catalfriend();
		}
		else
        {
        AlertDialog alertDialog = new AlertDialog.Builder(this).create();
		alertDialog.setTitle("Error");
		alertDialog.setMessage(Settings.gakonek);
		alertDialog.setButton("OK", new DialogInterface.OnClickListener() { 
			public void onClick(DialogInterface dialog, int which) {
			finish();
			}
		});
		alertDialog.setIcon(R.drawable.oc2);
		alertDialog.show();
        }
	}
	
	public void onResume()
	{
		super.onResume();
		if(!MusikLegal.internet(getApplicationContext()))
		{
			finish();
		}
		
	}
	
	void catalogue(){
			tv = (TextView)findViewById(R.id.onlinestore);
			tv.setText(thismerchant.name);
		 	lvc=(ListView)findViewById(R.id.CatView);
			
			 adapter2 = new InterfaceAdapter(this,OnlineC.catl); 
			 adapter2.notifyDataSetChanged();
			 lvc.setAdapter(adapter2);
			 lvc.setItemsCanFocus(true);
			
			 lvc.setOnScrollListener(new OnScrollListener(){

				public void onScroll(AbsListView view, int firstVisibleItem,
						int visibleItemCount, int totalItemCount) {
					int lastitem = firstVisibleItem + visibleItemCount;
					if(!loading&&lastitem == totalItemCount-1)
						{
						
						
						new Thread(new Runnable(){

							public void run() {
								loading =true;
								
										if(offset+24<=OnlineC.catl.size()){
					               			 try {
					               				 offset+=25;
					    						 //addres = "http://secure.musiklegal.com/?action=catalogue&method=get&api_key="+Browseby.apikey+"&limit=25&offset=";
					               				 addres.offset=offset;
					    						gets = new HttpGet(addres.toString());
					    						//cp = new CatalogueParser();
					    						
					    						//Toast.makeText(getApplicationContext(), addres.toString(), Toast.LENGTH_SHORT).show();
					    						Log.i("alamat",addres.toString());
												hrep = tinfo.execute(gets);
												trinfo = hrep.getEntity();
						               			spf = SAXParserFactory.newInstance();
						               			sp = spf.newSAXParser();
						               			xr = sp.getXMLReader();
						               			xr.setContentHandler(cp);
						               			xr.parse(retrieveInputStream(trinfo));
						               			OnlineC.catl.addAll(cp.catl);
						               			cp.catl.clear();
						               			h.post(new Runnable(){

													public void run() {
														
						               			lvc.invalidateViews();
													}});//lvc.in
						               			
											} catch (ClientProtocolException e) {
												// TODO Auto-generated catch block
												e.printStackTrace();
											} catch (IOException e) {
												// TODO Auto-generated catch block
												e.printStackTrace();
											} catch (ParserConfigurationException e) {
												// TODO Auto-generated catch block
												e.printStackTrace();
											} catch (SAXException e) {
												// TODO Auto-generated catch block
												e.printStackTrace();
											}
											loading = false;
											
											}
										
								
								
							}}).start();
						
						}
					
				}

				public void onScrollStateChanged(AbsListView view,
						int scrollState) {
				}});
			 
			 lvc.setOnItemClickListener(new OnItemClickListener() 
		        {
		          public void onItemClick(AdapterView<?> parent, View view,int position, long id) 
		          {
		        	  TrackInfo.isCatalogue=true;
		        	  try{
		        		  	TrackInfo.ds = (DataSong) lvc.getItemAtPosition(position);
		        			 TrackInfo.fromCatalogue=true;
		        			 TrackInfo.fromFriend=false;
		        			 TrackInfo.mercapi=merchant.id+"-"+merchant.key;
		        			 Intent i = new Intent(getApplicationContext(), TrackInfo.class);
		        			 //TrackInfo.isCatalogue = true;
		        			 startActivity(i);
		        	  }
		        	  catch (Exception e) {
		              }
		        	  }
		        });
			 
			 Button search = (Button) this.findViewById(R.id.src);
			 search.setOnClickListener(new OnClickListener() 
             {
                   public void onClick(View v) 
                   {
                	   OnlineC.catl.clear();
                	   
                	   try
                	   {   
                		   lvc.invalidateViews(); 
                		   EditText srctxt = (EditText) findViewById(R.id.search);
              			 	srch = srctxt.getText().toString().replace(" ", "+");
              			 	offset=1;
        	                 //gets = new HttpGet("http://secure.musiklegal.com/?action=catalogue&method=get&api_key="+Browseby.apikey+"&filter="+srch+"&limit=25&offset=1");
              			 	addres.offset = offset;
              			 	addres.filter = srch;
              			 	gets = new HttpGet(addres.toString());
              			 
                		     OnlineC.catl.clear();
                			 hrep = tinfo.execute(gets);
                			trinfo = hrep.getEntity();
                			 spf = SAXParserFactory.newInstance();
                			 sp = spf.newSAXParser();
                			 xr = sp.getXMLReader();
                			 
                			xr.setContentHandler(cp);
                			xr.parse(retrieveInputStream(trinfo));
                			
                			OnlineC.catl.addAll(cp.catl);
                			cp.catl.clear();
                			lvc.invalidateViews();
                			
                			srctxt.clearFocus();
                			
                	   }
                	   catch (Exception e) {
                		   
  		              }
                	   catalogue();
                   }
             });
		
	}
	
	void catalfriend()
	{
		
		tv = (TextView)findViewById(R.id.onlinestore);
		tv.setText( name+" TopPlay");
	 	lvc=(ListView)findViewById(R.id.CatView);
		
		 adapter2 = new InterfaceAdapter(this,OnlineC.catl); 
		 adapter2.notifyDataSetChanged();
		 lvc.setAdapter(adapter2);
		 lvc.setItemsCanFocus(true);
		
		 
		 lvc.setOnItemClickListener(new OnItemClickListener() 
	        {
	          public void onItemClick(AdapterView<?> parent, View view,int position, long id) 
	          {
	        	  TrackInfo.isCatalogue = false;
	        	  try{
	        		  	TrackInfo.ds = (DataSong) lvc.getItemAtPosition(position);
	        		  	
	        			 TrackInfo.fromCatalogue=true;
	        			 TrackInfo.fromFriend=true;
	        			 TrackInfo.mercapi=OnlineC.catl.get(position).api;
	        			 System.gc();
	        			 
	        			 Intent i = new Intent(getApplicationContext(), TrackInfo.class);
	        			 startActivity(i);
	        	  }
	        	  catch (Exception e) {
	              }
	        	  }
	        });
		 Button search = (Button) this.findViewById(R.id.src);
		 EditText srctxt = (EditText) findViewById(R.id.search);
		 search.setVisibility(View.GONE);
		 srctxt.setVisibility(View.GONE);
	}
	private InputSource retrieveInputStream(HttpEntity httpEntity) {
        InputSource insrc = null;
        try {
              insrc = new InputSource(httpEntity.getContent());
        } catch (Exception e) {
        }
        return insrc;
  }
	
	 protected Dialog onCreateDialog(int id) {
	        switch (id) {
	              case 0: {
	                    dialog = new ProgressDialog(this);
	                    dialog.setMessage("Loading...");
	                    dialog.setIndeterminate(true);
	                    dialog.setCancelable(true);
	                    return dialog;                   
	              }
	        }
	        return null;
	  }
	public void onDestroy()
	{
		thismerchant=null;
		super.onDestroy();
		if(adapter2!=null)
		adapter2.clear();
		System.gc();
	}
	 	
}

